<?php

namespace app\admin\controller\goods;

use app\admin\logic\GoodsLogic;
use app\admin\model\goods\GoodsSpec;
use app\common\controller\Backend;
use Exception;
use PDOException;
use think\Db;
use think\exception\DbException;
use think\exception\ValidateException;

/**
 * 商品
 *
 * @icon fa fa-circle-o
 */
class Goods extends Backend
{

    /**
     * Goods模型对象
     * @var \app\admin\model\goods\Goods
     */
    protected $model = null;
    protected $specList = [];
    protected $noNeedRight = ['ajaxGetSpecInput', 'getKeyNameByKey', 'spec'];
    protected $multiFields = ['is_index','status'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\goods\Goods;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("stockTypeList", $this->model->getStockTypeList());
        $this->view->assign("dispatchTypeList", $this->model->getDispatchTypeList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['category'])
//                ->withSum('spec','spec_stock')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('category');
                $row->spec_sum = model('app\admin\model\goods\GoodsSpec')->where(['goods_id' => $row->id])->sum('spec_stock');
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        $result = false;
        Db::startTrans();
        try {
//            if($params['is_index'] == 1) {
//                if(empty($params['coupon_exchange_id'])) {
//                    throw new Exception('请选择兑换活动');
//                }
//            }

            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);

            if(empty($params['dispatch_type'])){
                throw new Exception('请选择配送方式');
            }

            if(empty($params['item'])){
                throw new Exception('请填写规格参数');
            }
            $item = $params['item'];
            $specArray = [];

            // 组装规格项并创建
            foreach ($item as $key => $val){
                $spec_item_key = [];
                $spec_item_value = [];
                foreach ($val as $k => $v){
                    if(substr_count($k,'spec_group_')){
                        $spec_group_id = str_replace('spec_group_','',$k);
                        if(empty($v)){
                            throw new Exception('请填写规格项');
                        }
                        /* 2023-06-19 11:30:45 */
                        // 查询有没有对应的规格项,没有则添加,有则拿规格项ID
                        $specItem = model('GoodsSpecItem','model\goods')
                            ->get(['spec_group_id' => $spec_group_id,'item_name' => $v]);
                        if($specItem){
                            $specItemId = $specItem->spec_item_id;
                        }else{
                            $specItemId = model('GoodsSpecItem','model\goods')->insertGetId([
                                'spec_group_id' => $spec_group_id,
                                'item_name' => $v,
                            ]);
                        }
                        /* 2023-06-19 11:30:45 */
                        $spec_item_key[] = $specItemId;
                        $spec_item_value[] = $v;
                    }
                }
                if(empty($spec_item_key)){
                    throw new Exception('请填写正确的规格');
                }
                $spec_item_key = implode(',',$spec_item_key);
                $spec_item_value = implode(',',$spec_item_value);

                if (empty($val['spec_price']) || $val['spec_price'] == 0) {
                    throw new Exception('请填写规格价格');
                }
                if ($val['spec_stock'] === '') {
                    throw new Exception('请填写规格库存');
                }
                if (empty($val['weight'])) {
                    $item[$key]['weight'] = 0;
                }
                $specArray[$key]['goods_id'] = $this->model->id;
                $specArray[$key]['goods_spec_sn'] = $val['goods_spec_sn'];
                $specArray[$key]['spec_item_key'] = $spec_item_key;
                $specArray[$key]['spec_item_value'] = $spec_item_value;
                $specArray[$key]['spec_price'] = $val['spec_price'];
                $specArray[$key]['spec_stock'] = $val['spec_stock'];
                $specArray[$key]['spec_image'] = $val['spec_image'];
                $specArray[$key]['unit'] = $val['unit'];
                $specArray[$key]['weight'] = $val['weight'];
                /* 2023-06-13 16:48 */
                $specArray[$key]['status'] = $val['status'];
                /* 2023-06-13 16:48 */
                $specArray[$key]['createtime'] = time();
            }

            if(empty($specArray)){
                throw new Exception('请填写正确的规格');
            }

            model('app\admin\model\goods\GoodsSpec')->insertAll($specArray);

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param null $ids
     * @return string
     * @throws \think\Exception
     * @throws DbException
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
//            $spec = GoodsSpec::where(['goods_id' => $ids])->whereNull('deletetime')->select();
//            $this->assignconfig('spec', $spec);
            $this->view->assign('row', $row);
            $this->view->assign('goods_id', $ids);
            $this->assignconfig('goods_id', $ids);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
//            if($params['is_index'] == 1) {
//                if(empty($params['coupon_exchange_id'])) {
//                    throw new Exception('请选择兑换活动');
//                }
//            }

            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);

            if(empty($params['dispatch_type'])){
                throw new Exception('请选择配送方式');
            }

            if(empty($params['item'])){
                throw new Exception('请填写规格列表');
            }
            $item = $params['item'];
            $specArray = [];

            // 组装规格项并创建
            foreach ($item as $key => $val){
                $spec_item_key = [];
                $spec_item_value = [];
                foreach ($val as $k => $v){
                    if(substr_count($k,'spec_group_')){
                        $spec_group_id = str_replace('spec_group_','',$k);
                        if(empty($v)){
                            throw new Exception('请填写规格项');
                        }
                        // 查询有没有对应的规格项,没有则添加,有则拿规格项ID
                        $specItem = model('GoodsSpecItem','model\goods')
                            ->get(['spec_group_id' => $spec_group_id,'item_name' => $v]);
                        if($specItem){
                            $specItemId = $specItem->spec_item_id;
                        }else{
                            $specItemId = model('GoodsSpecItem','model\goods')->insertGetId([
                                'spec_group_id' => $spec_group_id,
                                'item_name' => $v,
                            ]);
                        }
                        $spec_item_key[] = $specItemId;
                        $spec_item_value[] = $v;
                    }
                }
                if(empty($spec_item_key)){
                    throw new Exception('请填写正确的规格');
                }
                $spec_item_key = implode(',',$spec_item_key);
                $spec_item_value = implode(',',$spec_item_value);

                if (empty($val['spec_price']) || $val['spec_price'] == 0) {
                    throw new Exception('请填写规格价格');
                }
                if ($val['spec_stock'] === '') {
                    throw new Exception('请填写规格库存');
                }
                if (empty($val['weight'])) {
                    $item[$key]['weight'] = 0;
                }
                $specArray[$key]['goods_spec_id'] = empty($val['goods_spec_id'])?null:$val['goods_spec_id'];
                $specArray[$key]['goods_id'] = $row->id;
                $specArray[$key]['goods_spec_sn'] = $val['goods_spec_sn'];
                $specArray[$key]['spec_item_key'] = $spec_item_key;
                $specArray[$key]['spec_item_value'] = $spec_item_value;
                $specArray[$key]['spec_price'] = $val['spec_price'];
                $specArray[$key]['spec_stock'] = $val['spec_stock'];
                $specArray[$key]['spec_image'] = $val['spec_image'];
                $specArray[$key]['unit'] = $val['unit'];
                $specArray[$key]['weight'] = $val['weight'];
                /* 2023-06-13 16:48 */
                $specArray[$key]['status'] = $val['status'];
                /* 2023-06-13 16:48 */
                $specArray[$key]['createtime'] = time();
            }

            if(empty($specArray)){
                throw new Exception('请填写正确的规格');
            }

            $result = model('GoodsSpec','model\goods')->saveAll($specArray);

        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        Db::commit();
        $this->success();
    }

    /**
     * 获取商品规格数据
     */
    public function spec($ids = null)
    {
        $spec = model('GoodsSpec','model\goods')
            ->where(['goods_id' => $ids])
            ->whereNull('deletetime')
            ->select();
        if (!$spec) {
            $this->error(__('No Results were found'));
        }
        foreach ($spec as $row){
            $row->goods_spec_item = model('GoodsSpecItem','model\goods')
                ->whereIn('spec_item_id',$row->spec_item_key)
                ->where('status',1)
                ->select();
        }
        $this->success('请求成功','',$spec);
    }

    /**
     * 动态获取商品规格输入框 根据不同的数据返回不同的输入框
     */
    public function ajaxGetSpecInput()
    {
        $GoodsLogic = new GoodsLogic();
        $goods_id = input('goods_id/d') ? input('goods_id/d') : 0;
        $str = $GoodsLogic->getSpecInput($goods_id, input('post.spec_arr/a', [[]]));
        return $str;
    }

    private function getKeyNameByKey($key)
    {
        $keyArray = explode(',',$key);
        $data = \app\admin\model\goods\GoodsSpecItem::all($keyArray,['specGroup']);
        $keyName = '';
        foreach ($data as $v) {
//            $keyName .= $v['spec']['item'];
            $keyName .= $v['specGroup']['spec_name'];
            $keyName .= ':';
            $keyName .= $v['item_name'];
            $keyName .= ' ';
        }
        return $keyName;
    }


}
